#region (c) 2014 THN Solutions LLC. - All rights reserved
/*
Simplified BSD License (BSD)
Copyright (c) 2014, THN Solutions LLC. ( www.ThnSolutions.com )
Author: Nguyễn, M. Hải                 ( www.Minh-Hai.com     )
All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice, this 
      list of conditions and the following disclaimer.

    * Redistributions in binary form must reproduce the above copyright notice, 
      this list of conditions and the following disclaimer in the documentation 
      and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
POSSIBILITY OF SUCH DAMAGE.
*/
#endregion

#region Record of Change
//             							CHANGE HISTORY
// -------------------------------------------------------------------------------------
// |   DATE    | DEVELOPER  | DESCRIPTION                                              |
// -------------------------------------------------------------------------------------
// | 13-Nov-09 | LamNPT      | First creation.                                          |
// -------------------------------------------------------------------------------------
//
#endregion

#region Record of Audit
//             							REVIEW HISTORY
// -------------------------------------------------------------------------------------
// |   DATE    | REVIEWER   | NOTES                                                    |
// -------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------
//
#endregion

#region Using directives
using System;

using Thn;
using Thn.Interface.Utils;
#endregion

namespace Thn.Interface.Vcl
{
    /// <summary>
    /// A helper class for smart parsing of date value from string.
    /// <para>This parser accepts minimal input styles such as: date only, date and month, date-month-year. Supports both English and Vietnamese</para>
    /// </summary>
#if DEBUG 
    public
#else
    internal
#endif 
    class DateParser
    {
        #region Parse
        /// <summary>
        /// Parse a date value from string input.
        /// <para>When input contains 1-2 digit characters, automatically guess it as day component. Month and Year will be current time</para>
        /// <para>When input contains 3-6 digit characters, guess input as day+month or day/month. Year will be current time</para>
        /// <para>When input contains more than 5 digit characters, guess input with all 3 components: day, month, year</para>
        /// </summary>
        /// <param name="input">day; day and month; day, month and year</param>
        public DateTime Parse(string input)
        {
            DateTime result = DateTime.Now;

            if (string.IsNullOrEmpty(input))
            {
                //Thn.Exceptions.NullArgumentException.Publish("input");
                throw new Exception("Input value is null or empty.");
            }
            else
            {
                //remove space
                input = RemoveSpace(input);

                //invalid input data
                if (input == "")
                {
                    throw new Exception("Input value is null or empty.");
                }
                else
                {
                    string[] splitString;
                    splitString = SplitString(input);

                    //check common valid
                    //is numeric
                    //great than 0
                    if (CheckCommon(splitString))
                        //check valid value by language
                        result = GetDateTime(splitString);
                }
            }

            return result;
        }
        #endregion

        #region tackle string
        /// <summary>
        /// Remove space in string
        /// </summary>
        private string RemoveSpace(string input)
        {
            string temp = "";
            for (int i = 0; i < input.Length; i++)
            {
                if (input[i] != ' ')
                    temp += input[i];
            }

            return temp;
        }

        private string[] SplitString(string input)
        {
            if (input.IndexOf('-') != -1)
            {
                input = SlimString(input, '-');
                return input.Split('-');
            }
            else
            {
                input = SlimString(input, '/');
                return input.Split('/');
            }
        }

        private string SlimString(string input, char seperator)
        {
            int lengthInput = input.Length;
            int position = 0;
            while (position < lengthInput - 1)
            {
                if (input[position] == seperator & input[position + 1] == seperator)
                {
                    input = input.Remove(position, 1);
                    lengthInput = input.Length;
                }
                else
                {
                    position += 1;
                }
            }

            if (input[0] == seperator)
                input = input.Remove(0, 1);

            if (input[input.Length - 1] == seperator)
                input = input.Remove(input.Length - 1, 1);

            return input;
        }
        #endregion

        #region check string, used to all language

        /// <summary>
        /// Check common value
        /// + Is numeric
        /// + Great than 0
        /// </summary>
        private bool CheckCommon(string[] value)
        {
            int o = 1;

            for (int i = 0; i < value.Length; i++)
            {
                if (!int.TryParse(value[i], out o))
                {
                    //DateParserException.Publish_InvalidInput(value[i].ToString());
#if DEBUG
                    throw new NotSupportedException("Giá trị nhập vào phải là số");
#endif
                    return false;
                }

                if (o <= 0)
                {
                    //DateParserException.Publish_InvalidInput(o.ToString());
#if DEBUG
                    throw new NotSupportedException("Giá trị nhập vào phải lớn hơn 0");
#endif
                    return false;
                }
            }

            return true;
        }
        #endregion

        #region these function check valid and then calculate date for each language

        DateTime GetDateTime(string[] value)
        {
            int d, m, y;
            m = DateTime.Now.Month;
            y = DateTime.Now.Year;
            d = 1;
            int dt = 1;

            // dd/mm/yyyy
            int dIdx = DateTimeHelper.GetOrder(DateElement.Day);
            int mIdx = DateTimeHelper.GetOrder(DateElement.Month);
            int yIdx = DateTimeHelper.GetOrder(DateElement.Year);

            switch (value.Length)
            {
                case 1:
                    d = int.Parse(value[dIdx]);
                    dt = DateTime.DaysInMonth(y, m);
                    if (d > dt)
                    {
                        //ngày không hợp lệ đối tháng hiện tại - input: ngày
                        throw new Exception("Ngày " + d + " trong tháng " + m + " năm " + y + " không hợp lệ");
                    }
                    break;
                case 2:
                    d = int.Parse(value[dIdx]);
                    m = int.Parse(value[mIdx]);
                    if (m > 12)
                    {
                        throw new Exception("Tháng không được lớn hơn 12");
                    }

                    dt = DateTime.DaysInMonth(y, m);
                    if (d > dt)
                    {
                        //ngày không hợp lệ đối tháng hiện tại - input: ngày
                        throw new Exception("Ngày " + d + " trong tháng " + m + " năm " + y + " không hợp lệ");
                    }
                    break;
                case 3:
                    d = int.Parse(value[dIdx]);
                    m = int.Parse(value[mIdx]);
                    if (m > 12)
                    {
                        throw new Exception("Tháng không được lớn hơn 12");
                    }

                    y = DateTimeHelper.CalculateYear(y, int.Parse(value[yIdx]));

                    if (y > 9999)
                    {
                        throw new Exception("Năm phải nằm trong khoảng 1 - 9999");
                    }

                    dt = DateTime.DaysInMonth(y, m);
                    if (d > dt)
                    {
                        //ngày không hợp lệ đối tháng hiện tại - input: ngày
                        throw new Exception("Ngày " + d + " trong tháng " + m + " năm " + y + " không hợp lệ");
                    }
                    break;
                #region Defensive tracing
                default:
                    throw new Exception("Input value not valid.");
                #endregion
            }

            return new DateTime(y, m, d);
        }

        #endregion

        #region Constructors
        /// <summary>
        /// Default constructor
        /// </summary>
        public DateParser()
        { }
        #endregion
    }
}